package miku.firstgame.model.proxy
{
	import flash.media.Video;

	import miku.firstgame.constrants.AppConstrants;
	import miku.firstgame.constrants.ProtocalConstants;
	import miku.firstgame.model.Me;
	import miku.firstgame.model.Room;
	import miku.firstgame.model.User;
	import miku.firstgame.net.IConnection;
	import miku.firstgame.net.pack.AddRoomResponsePack;
	import miku.firstgame.net.pack.EnterRoomResponsePack;
	import miku.firstgame.net.pack.GetReadyResponsePack;
	import miku.firstgame.net.pack.RemoveRoomResponsePack;
	import miku.firstgame.net.pack.RoomMasterChangedResponsePack;
	import miku.firstgame.net.pack.SendUserACardResponsePack;
	import miku.firstgame.net.pack.UserEnterRoomResponsePack;
	import miku.firstgame.net.pack.UserGetReadyResponsePack;
	import miku.firstgame.net.proxy.Connection;

	import org.puremvc.as3.patterns.proxy.Proxy;

	public class RoomProxy extends Proxy
	{
		public static const NAME:String = "RoomProxy";

		public var rooms:Vector.<Room>;

		public function RoomProxy()
		{
			super(NAME);
			rooms = new Vector.<Room>();
		}

		override public function onRegister():void
		{
			super.onRegister();
			Connection.getInstance().registerProtocolInterest(handleAddRoom, [ProtocalConstants.ADD_ROOM]);
			Connection.getInstance().registerProtocolInterest(handleRemoveRoom, [ProtocalConstants.REMOVE_ROOM]);
			Connection.getInstance().registerProtocolInterest(handleEnterRoom, [ProtocalConstants.ENTER_ROOM]);
			Connection.getInstance().registerProtocolInterest(handleUserEnterRoom, [ProtocalConstants.USER_ENTER_ROOM]);
			Connection.getInstance().registerProtocolInterest(handleRoomMasterChange, [ProtocalConstants.ROOM_MASTER_CHANGE]);
			Connection.getInstance().registerProtocolInterest(handleGetReady, [ProtocalConstants.GET_READY]);
			Connection.getInstance().registerProtocolInterest(handleUserGetReady, [ProtocalConstants.USER_GET_READY]);

		}

		override public function onRemove():void
		{
			super.onRemove();
			Connection.getInstance().unregisterHandler(handleAddRoom);
			Connection.getInstance().unregisterHandler(handleRemoveRoom);
			Connection.getInstance().unregisterHandler(handleEnterRoom);
			Connection.getInstance().unregisterHandler(handleUserEnterRoom);
			Connection.getInstance().unregisterHandler(handleRoomMasterChange);
			Connection.getInstance().unregisterHandler(handleGetReady);
			Connection.getInstance().unregisterHandler(handleUserGetReady);

		}

		private function handleGetReady(pack:GetReadyResponsePack, connection:IConnection):void
		{
			if (pack.result != 0)
			{
				sendNotification(AppConstrants.GET_READY_FAIL);
			}
		}

		private function handleUserGetReady(pack:UserGetReadyResponsePack, connection:IConnection):void
		{
			var user:User = ProxyHelper.getUser(pack.userId);
			if (user)
			{
				user.isReady = pack.value;
				sendNotification(AppConstrants.USER_GET_READY, user);
			}
		}

		private function handleRoomMasterChange(pack:RoomMasterChangedResponsePack, connection:IConnection):void
		{
			var user:User = ProxyHelper.getUser(pack.userId);
			if (user)
			{
				Me.Instace.room.roomMaster = user;
				sendNotification(AppConstrants.ROOM_MASTER_CHANGED, user);
			}
		}

		private function handleEnterRoom(pack:EnterRoomResponsePack, connection:IConnection):void
		{
			if (pack.result == 0)
			{
				trace("进入房间成功");
				var room:Room = getRoom(pack.roomId);

				if (room)
				{
					Me.Instace.room = room;
					Me.Instace.setContactUsers(pack.users);

					var user:User = ProxyHelper.getUser(pack.masterId);
					if (user)
					{
						room.roomMaster = user;
					}

					sendNotification(AppConstrants.ENTER_ROOM_SUCCESS, room);

				}
				else
				{
					throw new Error("房间不存在");
				}

			}
			else if (pack.result == 2)
			{
				trace("房间人数已满");
				sendNotification(AppConstrants.ENTER_ROOM_MAX_USER_FAIL);
			}
			else
			{
				trace("进入房间失败");
				sendNotification(AppConstrants.ENTER_ROOM_FAIL);
			}
		}

		private function handleUserEnterRoom(pack:UserEnterRoomResponsePack, connection:IConnection):void
		{

			var room:Room = getRoom(pack.roomId);

			if (room)
			{
				var user:User = pack.user;
				Me.Instace.addContactUser(user);
				ProxyHelper.addUser(user);

				sendNotification(AppConstrants.USER_ENTER_ROOM, user);

			}
			else
			{
				throw new Error("房间不存在"); //更加友好的出错机制
			}
		}

		/**
		 * <rr id="" /> 房间人数不足导致删除房间
		 * */
		private function handleRemoveRoom(pack:RemoveRoomResponsePack, connection:IConnection):void
		{
			var room:Room = removeRoom(pack.roomId); //存在删除的房间，没有考虑分页 
			if (room)
			{
				sendNotification(AppConstrants.ROOM_REMOVED, room);
			}
		}

		public function addRoom(room:Room):void
		{
			rooms.push(room);
		}

		public function removeRoom(roomId:int):Room
		{
			var length:int = rooms.length;
			for (var i:int = 0; i < length; i++)
			{
				var room:Room = rooms[i];
				if (room.roomId == roomId)
				{
					rooms.splice(i, 1);
					return room;
				}
			}
			return null;
		}

		public function setRooms(rooms:Vector.<Room>):void
		{
			this.rooms = rooms;
		}

		public function getAllRoom():Vector.<Room>
		{
			return rooms;
		}

		public function clearAllRooms():void
		{
			rooms = new Vector.<Room>();
		}

		public function getRoom(id:int):Room
		{
			for each (var room:Room in rooms)
			{
				if (id == room.roomId)
				{
					return room;
				}
			}
			return null;
		}

		/**
		 *<ar r="0" n="" id = "" cid=""/> 需要考虑和Room.getInfo合并
		 *cid create id,创建房间用户的id
		 * */
		private function handleAddRoom(pack:AddRoomResponsePack, connection:IConnection):void
		{
			var result:Boolean = pack.result == 0;
			if (result)
			{
				var userId:int = pack.createUserId;
				var user:User = ProxyHelper.getUser(userId);
				if (!user) //创建房间的用户不存在，可能是出现错误或者不在大厅中
				{
					return;
				}

				var name:String = pack.roomName;
				var id:int = pack.roomId;

				var room:Room = new Room();
				room.roomId = id;
				room.roomName = name;
				room.roomMaster = user;
				addRoom(room);

				if (userId == Me.Instace.id) //表示自己添加的房间
				{ //直接创建成功，和别人创建成功
					Me.Instace.room = room;
				}

				sendNotification(AppConstrants.ROOM_ADD_SUCCESS, room);
			}
			else
			{
				sendNotification(AppConstrants.ROOM_ADD_FAIL);
			}
		}
	}
}
